import { getAllArea } from '@/services/common';
import { useFetch } from '@/pages/OrderModule/common/hooks/useFetch';
import { Select } from 'antd';
import { useEffect, useState } from 'react';
import IconFont from '@/components/IconFont';

function bfs(root) {
  let buff = root;
  const res = [buff];
  while (buff.length) {
    let tmp = [];
    for (let i = 0; i < buff.length; i++) {
      if (buff[i]?.childs) {
        tmp = tmp.concat(buff[i].childs);
      }
    }
    buff = tmp;
    res.push(tmp);
  }

  return {
    provinceIdArr: res[0],
    cityIdArr: res[1],
    districtIdArr: res[2],
  };
}

/**
 * 搜索地址组件
 * @param {*} props
 */
function SearchAddress(props) {
  const { data, fetch, loading } = useFetch(getAllArea, {}, true);
  const [areaList, setAreaList] = useState({
    provinceIdArr: [],
    cityIdArr: [],
    districtIdArr: [],
  });

  useEffect(() => {
    fetch().then((res) => {
      setAreaList(bfs(res.data));
    });
  }, []);

  return (
    <Select
      mode="multiple"
      allowClear
      placeholder="输入关键字"
      style={{ width: '100%' }}
      value={props.value}
      onChange={(val) => {
        props.onChange(val);
      }}
      filterOption={(input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
      options={areaList[props.type].map((item) => ({ value: item.id, label: item.name }))}
      clearIcon={<IconFont type="iconguanbi2fill" style={{fontSize:'14px'}} />}
    />
  );
}
export default SearchAddress;
